import axios from './request';
// import instance from './request';
import * as CryptoJS from 'crypto-js'; // 导入 CryptoJS 库和 AES 加密算法


// 公共加密函数
function encryptData(data: any, secretKey: string, iv: string): string {
    const ciphertext = CryptoJS.AES.encrypt(data, secretKey, {
        iv: CryptoJS.enc.Hex.parse(iv),
        padding: CryptoJS.pad.Pkcs7,
        mode: CryptoJS.mode.CBC,
    }).toString();
    return ciphertext;
}

// 公共解密函数
function decryptData(ciphertext: string, secretKey: string, iv: string): any {
    const bytes = CryptoJS.AES.decrypt(ciphertext, secretKey, {
        iv: CryptoJS.enc.Hex.parse(iv),
        padding: CryptoJS.pad.Pkcs7,
        mode: CryptoJS.mode.CBC,
    });
    return JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
}


// 请求处理函数
async function processRequest(method: string, path: string, data: any = null): Promise<any> {
    let result = await axios.get('/test');
    const secretKey = result.data.key
    const iv = result.data.iv
    if (!secretKey || !iv) {
        console.error('必须提供密钥和iv');
        throw new Error('Invalid encryption configuration');
    }
    let response;
    try {
        if (data) {
            const encryptedData = encryptData(JSON.stringify(data), secretKey, iv);
            if (method === 'get') {
                response = await axios({ method, url: path, params: { data: encryptedData } });
            } else {
                response = await axios({ method, url: path, data: { data: encryptedData } });
            }
        } else {
            response = await axios({ method, url: path });
        }

        // 解密返回数据
        // console.log(response.data.data)
        const decryptedData = decryptData(response.data.data, secretKey, iv);
        return { ...response.data, data: decryptedData };
    } catch (error) {
        console.error(`Error with ${method.toUpperCase()} request to ${path}:`, error);
        throw error;
    }
}

// 导出 API 请求函数
export const getData = (path: string) => processRequest('get', path);   //  不带参数
export const getQuery = (path: string, data: any) => processRequest('get', path, data);     //  携带参数
export const postData = (path: string, data: any) => processRequest('post', path, data);
export const putData = (path: string, data: any) => processRequest('put', path, data);
export const deleteData = (path: string, data: any) => processRequest('delete', path, data);
